import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-07-10
 * Time:22:23
 */
public class HelloServlet implements Servlet {
    private int counter = 0;

    /**
     * 1.初始化Servlet
     * 2.当Tomcat创建HelloServlet实例时,会调用该方法
     * 3.该方法在对象生命周期只会被调用一次
     *
     * @param servletConfig
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("Init servlet");
    }

    /**
     * 返回Servlet的配置
     *
     * @return
     */
    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * 1.该方法处理浏览器的请求(包括GET/POST...)
     * 2.浏览器每次请求Servlet时,该方法都会被Tomcat调用一次
     * 3.当Tomcat调用该方法时
     *      1'开一个线程
     *      2'将HTTP请求的数据封装成实现ServletRequest接口的request对象 | 实例化一个代表HTTP响应,实现ServletResponse接口的response对象
     *      3'将request和response对象作为参数传入
     * 4.servletResponse对象可以用于返回响应数据给Tomcat,通过Tomcat传HTTP响应给浏览器
     *
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Hello servlet");
        //Servlet是单例
        System.out.println("counter: " + (++counter));
        //Tomcat每次处理HTTP请求时,会生成一个线程调用该方法
        System.out.println("thread id: " + (Thread.currentThread().getId()));

        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        String method = httpServletRequest.getMethod();
        if (method.equals("GET")) {
            doGet();
        } else if (method.equals("POST")) {
            doPost();
        }
    }

    private void doGet() {
        System.out.println("doGet");
    }
    private void doPost() {
        System.out.println("doPost");
    }
    /**
     * 返回Servlet信息
     *
     * @return
     */
    @Override
    public String getServletInfo() {
        return "";
    }

    /**
     * 1.该方法只有在对象被销毁时被调用
     * 2.只会被调用一次
     */
    @Override
    public void destroy() {
        System.out.println("Destroying servlet");
    }
}
